package com.roc.web.action.agent;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblTermInf;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IorgService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;
/**
 * fupan
 * @author Administrator
 *
 */
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/merinfo")
public class MerinfoStatisticsAction extends PaginationBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	static Logger logger = LogManager.getLogger(MerinfoStatisticsAction.class);

	private Long psamCardStartNo;
	private Long psamCardEndNo;
	private Long totalNum;
	private MerinfoStatisticsSearchCondition searchCondition;

	private List<TblInsInf> orgList = new ArrayList<TblInsInf>();

	private InputStream excelFile;
	private String excelName;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	IExcelService excelService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IorgService orgService;
	

	@Action(value = "merinfoStatisticsInit", results = {
			@Result(name = "success", location = "/pages/merinfo/merinfoStatistics.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String termQrtInit() throws Exception {
		Operators loginOperator = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		if(loginOperator.getRoleType().equals(Role.AGENT.getCode()) && !loginOperator.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		if(!loginOperator.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		// 加载数据
		org();

		searchCondition = new MerinfoStatisticsSearchCondition();
		// 默认查询当天日期
		String today = Constance.currTime();
		searchCondition.setMinDate(today);
		searchCondition.setMaxDate(today);
		
		return SUCCESS;
	}

	@Action(value = "queryMerinfoStatisticsList", results = { @Result(name = "success", location = "/pages/merinfo/merinfoStatistics.jsp") })
	// 查询代理商统计信息
	public String queryTerminalPosSNAction() throws Exception {

		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		if (searchCondition == null) {
			searchCondition = (MerinfoStatisticsSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new MerinfoStatisticsSearchCondition();
			}
		}
		try {
			
			if(!op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();
			/*
			// 设置机构号
			List<TblInsInf> orgList= orgService.queryOrgList();
			searchCondition.setOrgCode(orgList.get(0).getInsIdCd());
			*/
			List<Operators> lowOneList = new ArrayList<Operators>();
	//		List<List<Operators>> operatorsLists = new ArrayList<List<Operators>>();
			List<String> operatorsLists = new ArrayList<String>();
			
			// 如果选中了代理商,查询此代理商下的信息
			if(null != searchCondition.getAgentId() && !searchCondition.getAgentId().trim().equals("-1")){
				String supId = Constant.SHOUDANSHIYEBU_ID;
				List<Operators> opBeanList = merchantServices.queryLowOneAgent(supId);
		//		List<Operators> opList=merchantServices.listAllSubMerchants(Long.parseLong(searchCondition.getAgentId()));
				for (Operators operators : opBeanList) {
					if(String.valueOf(operators.getId()).equals(searchCondition.getAgentId())){
						lowOneList.add(operators);
					}
				}
				operatorsLists.add(searchCondition.getAgentId());
			} else{
				String supId = Constant.SHOUDANSHIYEBU_ID;
				lowOneList = merchantServices.queryLowOneAgent(supId);
				for (Operators operators : lowOneList) {
				//	List<Operators> opList = merchantServices.listAllSubMerchants(operators.getId());
					
					operatorsLists.add(String.valueOf(operators.getId()));
				}
			}

			List<TblMchtInf> opBeanList = new ArrayList<TblMchtInf>();
			if(operatorsLists != null && operatorsLists.size() > 0 ){

				for (int s = 0; s < operatorsLists.size(); s++ ) {
					String aId = operatorsLists.get(s);
				/*	List<Operators> list = operatorsLists.get(s);
					String[]  agentList= new String[list.size()];
					for (int i=0;i<list.size();i++) {
						Operators o=list.get(i);
						agentList[i]=Long.toString(o.getId());
					}
				    searchCondition.setAgentIdList(agentList);*/
				    searchCondition.setObj(aId);
				    int rows = pagenitionService.countSQL(searchCondition);
				    if(rows > 0){
					    List<Object> rsList = pagenitionService.findAllSQL(searchCondition,
								calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
						if (rsList != null && rsList.size() > 0) {
							Iterator iterator = rsList.iterator();
							while (iterator.hasNext()) {
								Object[] obj = (Object[]) iterator.next();
								TblMchtInf bean = new TblMchtInf();
								TblTermInf termBean = new TblTermInf();
								List<TblTermInf> terminfoList = new ArrayList<TblTermInf>();
								
								if (obj[0] != null && !"".equals(obj[0])) {
									bean.setApplDate(obj[0].toString());
								}
								if (obj[1] != null && !"".equals(obj[1])) {
								//	bean.setMCHTCD
									bean.setId(obj[1].toString());
								}
								if (obj[2] != null && !"".equals(obj[2])) {
									termBean.getId().setTermId(obj[2].toString());
								}
								if (obj[3] != null && !"".equals(obj[3])) {
									bean.setNameBusi(obj[3].toString());
								}
								if (obj[4] != null && !"".equals(obj[4])) {
									bean.setName(obj[4].toString());
								}
								if (obj[5] != null && !"".equals(obj[5])) {
									bean.setBusiLiceNo(obj[5].toString());
								}
								if (obj[6] != null && !"".equals(obj[6])) {
									bean.setBankBelongCd(obj[6].toString());
								}
								if (obj[7] != null && !"".equals(obj[7])) {
									bean.setExt1(Constance.Null2EmptyTrim(obj[7].toString()));
						//			bean.setAgentId(Constance.Null2EmptyTrim(obj[12]));1//所属代理商
								}
								if (obj[8] != null && !"".equals(obj[8])) {
								//	bean.setFINALARRPOVALUSERNAME
									bean.setBus_lic(Constance.Null2EmptyTrim(obj[8]));//审核人员名称
								}
								if (obj[9] != null && !"".equals(obj[9])) {
									bean.setStatus(MerinfoStatus.getName(obj[9].toString()));
								}
								if (obj[10] != null && !"".equals(obj[10])) {
									bean.setContactName(obj[10].toString());
								}
								if (obj[11] != null && !"".equals(obj[11])) {
									bean.setContactPhoneNo(obj[11].toString());
								}
								if (obj[12] != null && !"".equals(obj[12])) {
									bean.setCertif(obj[12].toString());
								}
								if (obj[13] != null && !"".equals(obj[13])) {
									bean.setCertifNo(obj[13].toString());
								}
								if (obj[14] != null && !"".equals(obj[14])) {
									bean.setUpMccCd(obj[14].toString());
								}
								if (obj[15] != null && !"".equals(obj[15])) {
									bean.setRegAddr(obj[15].toString());
								}
								if (obj[16] != null && !"".equals(obj[16])) {
									termBean.setTermTp(obj[16].toString());
								}
								if (obj[17] != null && !"".equals(obj[17])) {
									termBean.setInstalllocation(obj[17].toString());
								}
								terminfoList.add(termBean);
								bean.setTerminfoList(terminfoList);
								bean = merchantServices.queryOtherMerinfoInfo(bean.getId(), true, bean);
// bean.getId() 商户号
								String[] cycleList=merchantServices.queryMchtBizDealArray(bean.getId(),true,true);//根据商户查询结算周期
								bean.setMerCycle(cycleList);
								opBeanList.add(bean);
							}
						}
				    }
				    
				}
		
			}
			searchRsList.clear();
			searchRsList.addAll(opBeanList);
			this.setTotalPage(this.calcuTotalPage(opBeanList.size()));
			addActionMessage("当前条件下统计到【"+opBeanList.size()+"】条记录");
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	// 导出excel
	@Action(value = "excelMerinfoStatisticsList", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String settingExcelqQuery() throws Exception {
		try {
			
			Operators op = (Operators) ActionContext.getContext()
			.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
			
			
			if (searchCondition == null) {
				searchCondition = (MerinfoStatisticsSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new MerinfoStatisticsSearchCondition();
				}
			}
			
			if(!op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();

			// 设置机构号
			List<TblInsInf> orgList= orgService.queryOrgList();
			searchCondition.setOrgCode(orgList.get(0).getInsIdCd());
			
			List<Operators> lowOneList = new ArrayList<Operators>();
			List<String> operatorsLists = new ArrayList<String>();
			
			// 如果选中了代理商,查询此代理商下的信息
			if(null != searchCondition.getAgentId() && !searchCondition.getAgentId().trim().equals("-1")){
				String supId = Constant.SHOUDANSHIYEBU_ID;
				List<Operators> opBeanList = merchantServices.queryLowOneAgent(supId);
		//		List<Operators> opList=merchantServices.listAllSubMerchants(Long.parseLong(searchCondition.getAgentId()));
				for (Operators operators : opBeanList) {
					if(String.valueOf(operators.getId()).equals(searchCondition.getAgentId())){
						lowOneList.add(operators);
					}
				}
				operatorsLists.add(searchCondition.getAgentId());
			} else{
				String supId = Constant.SHOUDANSHIYEBU_ID;
				lowOneList = merchantServices.queryLowOneAgent(supId);
				for (Operators operators : lowOneList) {
				//	List<Operators> opList = merchantServices.listAllSubMerchants(operators.getId());
					
					operatorsLists.add(String.valueOf(operators.getId()));
				}
			}
			
			List<TblMchtInf> opBeanList = new ArrayList<TblMchtInf>();
			if(operatorsLists != null && operatorsLists.size() > 0 ){

				for (int s = 0; s < operatorsLists.size(); s++ ) {
					String aId = operatorsLists.get(s);/*
					List<Operators> list = operatorsLists.get(s);
					String[]  agentList= new String[list.size()];
					for (int i=0;i<list.size();i++) {
						Operators o=list.get(i);
						agentList[i]=Long.toString(o.getId());
					}
				    searchCondition.setAgentIdList(agentList);*/
				    searchCondition.setObj(aId);
				    int rows = pagenitionService.countSQL(searchCondition);
				    if(rows > 0){
					    List<Object> rsList = pagenitionService.findAllSQL(searchCondition,
								calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
						if (rsList != null && rsList.size() > 0) {
							Iterator iterator = rsList.iterator();
							while (iterator.hasNext()) {
								Object[] obj = (Object[]) iterator.next();
								TblMchtInf bean = new TblMchtInf();
								TblTermInf termBean = new TblTermInf();
								List<TblTermInf> terminfoList = new ArrayList<TblTermInf>();
								
								if (obj[0] != null && !"".equals(obj[0])) {
									bean.setApplDate(obj[0].toString());
								}
								if (obj[1] != null && !"".equals(obj[1])) {
								//	bean.setMCHTCD
									bean.setId(obj[1].toString());
								}
								if (obj[2] != null && !"".equals(obj[2])) {
									termBean.getId().setTermId(obj[2].toString());
								}
								if (obj[3] != null && !"".equals(obj[3])) {
									bean.setNameBusi(obj[3].toString());
								}
								if (obj[4] != null && !"".equals(obj[4])) {
									bean.setName(obj[4].toString());
								}
								if (obj[5] != null && !"".equals(obj[5])) {
									bean.setBusiLiceNo(obj[5].toString());
								}
								if (obj[6] != null && !"".equals(obj[6])) {
									bean.setBankBelongCd(obj[6].toString());
								}
								if (obj[7] != null && !"".equals(obj[7])) {
									bean.setExt1(Constance.Null2EmptyTrim(obj[7].toString()));
						//			bean.setAgentId(Constance.Null2EmptyTrim(obj[12]));1//所属代理商
								}
								if (obj[8] != null && !"".equals(obj[8])) {
								//	bean.setFINALARRPOVALUSERNAME
									bean.setBus_lic(Constance.Null2EmptyTrim(obj[8]));//审核人员名称
								}
								if (obj[9] != null && !"".equals(obj[9])) {
									bean.setStatus(MerinfoStatus.getName(obj[9].toString()));
								}
								if (obj[10] != null && !"".equals(obj[10])) {
									bean.setContactName(obj[10].toString());
								}
								if (obj[11] != null && !"".equals(obj[11])) {
									bean.setContactPhoneNo(obj[11].toString());
								}
								if (obj[12] != null && !"".equals(obj[12])) {
									bean.setCertif(obj[12].toString());
								}
								if (obj[13] != null && !"".equals(obj[13])) {
									bean.setCertifNo(obj[13].toString());
								}
								if (obj[14] != null && !"".equals(obj[14])) {
									bean.setUpMccCd(obj[14].toString());
								}
								if (obj[15] != null && !"".equals(obj[15])) {
									bean.setRegAddr(obj[15].toString());
								}
								if (obj[16] != null && !"".equals(obj[16])) {
									termBean.setTermTp(obj[16].toString());
								}
								if (obj[17] != null && !"".equals(obj[17])) {
									termBean.setInstalllocation(obj[17].toString());
								}
								terminfoList.add(termBean);
								bean.setTerminfoList(terminfoList);
								bean = merchantServices.queryOtherMerinfoInfo(bean.getId(), true, bean);
// bean.getId() 商户号
								String[] cycleList=merchantServices.queryMchtBizDealArray(bean.getId(),true,true);//根据商户查询结算周期
								bean.setMerCycle(cycleList);
								opBeanList.add(bean);
							}
						}
				    }   
				}
			}
			setExcelName(new String("商户信息导出".getBytes(), "ISO8859-1"));

			HSSFWorkbook work = excelService.statisticsMerinfoTransQueryExcel(opBeanList,searchCondition.getMinDate(),searchCondition.getMaxDate());
			ByteArrayOutputStream output = new ByteArrayOutputStream();  
			work.write(output);  
			   
			byte[] ba = output.toByteArray();  
			excelFile = new ByteArrayInputStream(ba);  
			output.flush();  
			output.close(); 
		} catch (Exception e) {
			logger.info("######商户信息导出Excel明细失败######");
			addActionError(e.getMessage());
			return ERROR;
		} 
		return SUCCESS;
	}
	
	// 加载数据
	public void org() throws Exception{
		List<Operators> opList = new ArrayList<Operators>();
		// 收单事业部Id
		String supId = Constant.SHOUDANSHIYEBU_ID;
		// 查询某个代理商的直属代理商
		opList = merchantServices.queryLowOneAgent(supId);
		getRequest().setAttribute("opList", opList);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (MerinfoStatisticsSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_TERM_SN_IMPORT);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERM_SN_IMPORT,
				searchCondition);
	}

	public Long getPsamCardStartNo() {
		return psamCardStartNo;
	}

	public void setPsamCardStartNo(Long psamCardStartNo) {
		this.psamCardStartNo = psamCardStartNo;
	}

	public Long getPsamCardEndNo() {
		return psamCardEndNo;
	}

	public void setPsamCardEndNo(Long psamCardEndNo) {
		this.psamCardEndNo = psamCardEndNo;
	}

	public Long getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(Long totalNum) {
		this.totalNum = totalNum;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public MerinfoStatisticsSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(MerinfoStatisticsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}



}
